<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="rolesDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(v1, i1) of scope.row.children"
              :key="v1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, v1.id)">{{
                  v1.authName
                }}</el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(v2, i2) of v1.children"
                  :key="v2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, v2.id)"
                      >{{ v2.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="v3 of v2.children"
                      :key="v3.id"
                      closable
                      @close="removeRightById(scope.row, v3.id)"
                      >{{ v3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="290">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色信息"
      :visible.sync="rolesDialogVisible"
      width="50%"
      @close="roleDialogClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="rolesForm"
        :rules="rolesFormRules"
        ref="rolesFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色信息"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        :props="treeProps"
        node-key="id"
        :default-checked-keys="defKeys"
        show-checkbox
        default-expand-all
      ></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      rolesDialogVisible: false,
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: []
      },
      editRoleDialogVisible: false,
      editRoleForm: {},
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: []
      },
      setRightDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: ''
    }
  },
  methods: {
    async getRolesList() {
      let res = await this.$http.get('/roles')
      if (res.meta.status === 200) {
        this.rolesList = res.data
      } else {
        this.$message({
          type: 'error',
          message: '获取角色列表失败!',
          duration: 1500
        })
        return false
      }
    },
    roleDialogClose() {
      this.$refs.rolesFormRef.resetFields()
    },
    addRole() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (valid) {
          let res = await this.$http.post('/roles', this.rolesForm)
          if (res.meta.status === 201) {
            this.rolesDialogVisible = false
            this.getRolesList()
            this.$message({
              type: 'success',
              message: '添加角色成功!',
              duration: 1500
            })
          } else {
            this.$message({
              type: 'error',
              message: '添加角色失败!',
              duration: 1500
            })
            return false
          }
        } else {
          return false
        }
      })
    },
    async removeRoleById(id) {
      let confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmResult === 'confirm') {
        let res = await this.$http.delete('/roles/' + id)
        if (res.meta.status === 200) {
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '已删除成功!',
            duration: 1500
          })
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!',
            duration: 1500
          })
          return false
        }
      } else {
        this.$message({
          type: 'info',
          message: '已取消了删除!',
          duration: 1500
        })
        return false
      }
    },
    async showEditDialog(id) {
      this.editRoleDialogVisible = true
      let res = await this.$http.get('/roles/' + id)
      if (res.meta.status === 200) {
        this.editRoleForm = res.data
        this.$message({
          type: 'success',
          message: '查询角色成功!',
          duration: 1500
        })
      } else {
        this.$message({
          type: 'error',
          message: '查询角色失败!',
          duration: 1500
        })
        return false
      }
    },
    editRoleDialogClose() {
      this.$refs.editRoleFormRef.resetFields()
    },
    editRoleInfo() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (valid) {
          let res = await this.$http.put(
            '/roles/' + this.editRoleForm.roleId,
            this.editRoleForm
          )
          if (res.meta.status === 200) {
            this.editRoleDialogVisible = false
            this.getRolesList()
            this.$message({
              type: 'success',
              message: '编辑角色成功!',
              duration: 1500
            })
          } else {
            this.$message({
              type: 'error',
              message: '编辑角色失败!',
              duration: 1500
            })
            return false
          }
        } else {
          return false
        }
      })
    },
    async removeRightById(role, rightId) {
      let confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmResult === 'confirm') {
        let res = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status === 200) {
          role.children = res.data
          this.$message({
            type: 'success',
            message: '删除权限成功!',
            duration: 1500
          })
        } else {
          this.$message({
            type: 'error',
            message: '删除权限失败!',
            duration: 1500
          })
          return false
        }
      } else {
        this.$message({
          type: 'info',
          message: '已取消了删除!',
          duration: 1500
        })
        return false
      }
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      let res = await this.$http.get('/rights/tree')
      if (res.meta.status === 200) {
        this.setRightDialogVisible = true
        this.getLeafKeys(role, this.defKeys)
        this.rightsList = res.data
        this.$message({
          type: 'success',
          message: '获取角色权限成功!',
          duration: 1500
        })
      } else {
        this.$message({
          type: 'error',
          message: '获取角色权限失败!',
          duration: 1500
        })
        return false
      }
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(v => {
          this.getLeafKeys(v, arr)
        })
      }
    },
    setRightDialogClose() {
      this.defKeys = []
    },
    async allotRights() {
      let keysStr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ].join(',')
      let res = await this.$http.post(`/roles/${this.roleId}/rights`, {
        rids: keysStr
      })
      if (res.meta.status === 200) {
        this.setRightDialogVisible = false
        this.getRolesList()
        this.$message({
          type: 'success',
          message: '分配角色权限成功!',
          duration: 1500
        })
      } else {
        this.$message({
          type: 'error',
          message: '分配角色权限失败!',
          duration: 1500
        })
        return false
      }
    }
  },
  mounted() {
    this.getRolesList()
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
